using System;
using System.Threading;
using HCP.Responses;

namespace HCP
{
	public class Job : IDisposable
	{
		public JobRequest Request { get; set; }

		public JobResponse Response { get; set; }

		public Job.EState State { get; set; }

		public bool IsComplete
		{
			get
			{
				return this.State == Job.EState.COMPLETE || this.State == Job.EState.ERROR;
			}
		}

		public void Await()
		{
			this.m_processReset.WaitOne();
		}

		public virtual void Process()
		{
			if (this.State == Job.EState.IDLE)
			{
				this.m_processReset.Reset();
			}
			this.State = Job.EState.RUNNING;
			try
			{
				this.Response = this.Request.Process();
				if (this.Response != null)
				{
					this.State = Job.EState.COMPLETE;
					this.Response.Status = JobResponse.EStatus.Success;
				}
			}
			catch (Exception ex)
			{
				this.State = Job.EState.ERROR;
				this.Response = new StringResponse(ex.Message);
				this.Response.Status = JobResponse.EStatus.UnhandledError;
			}
			finally
			{
				this.m_processReset.Set();
			}
		}

		public void Dispose()
		{
			this.m_processReset.Close();
		}

		public ManualResetEvent m_processReset = new ManualResetEvent(false);

		public enum EState
		{
			IDLE,
			RUNNING,
			COMPLETE,
			ERROR
		}
	}
}
